package com.woniuxy.third.controller;

import com.woniuxy.third.annotation.RequirePermission;
import com.woniuxy.third.entity.Role;
import com.woniuxy.third.entity.User;
import com.woniuxy.third.result.ResponseResult;
import com.woniuxy.third.service.RoleService;
import com.woniuxy.third.service.UserService;
import com.woniuxy.third.utils.GetUserUtil;
import com.woniuxy.third.utils.JwtUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Author: yangtao
 * @date 2021/7/14 10:45
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger logger= LoggerFactory.getLogger(UserController.class);
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    @PostMapping("/login")
    @ApiOperation(value = "登录",notes = "返回用户及权限信息")
    public ResponseResult<User> login(@RequestBody User user, HttpServletResponse response, HttpServletRequest request){
        //得到token
        String token1 = request.getHeader("authorization");
        if (token1 != null) {
            return new ResponseResult<>(201,"请勿重新登录",null);
        }

        //逻辑：用账号查询出结果，然后进行对比，在进行下一步操作
        User result = userService.findByAccount(user.getAccount());
        //假设查询出来了
        if (user.getAccount().equals(result.getAccount())&&user.getPwd().equals(result.getPwd())){
            logger.debug("登录成功");
            List<Role> rolesByUid = roleService.findRolesByUid(result.getId());
            result.setRoles(rolesByUid);
            //登录成功，生成一个token(jwt)返回前端浏览器
            String token = JwtUtil.generateToken(user.getAccount());
            //将token放到响应头
            response.setHeader("authorization",token);
            //将响应头暴露给第三方
            response.setHeader("Access-Control-Expose-Headers","authorization");
            //将当前用户信息放到session中
            logger.debug(result.toString());
            return new ResponseResult<>(200,"success",result);
        }else{
            logger.debug("失败");
            return new ResponseResult<>(500,"账号密码不匹配",null);
        }
        //将数据进行封装返回
    }
    /*@RequirePermission("user:find")*/
    @GetMapping("/all")
    @ApiOperation(value = "根据token拿到user",notes = "返回user数据")
    public ResponseResult<User> findUser(HttpServletRequest request){
        User user = GetUserUtil.getUser(request);
        if (user != null) {
            return new ResponseResult<>(200,"查询成功",user);
        }
        return new ResponseResult<>(500,"查询失败",null);
    }

    @PostMapping("/updateBalance")
    @ApiOperation(value = "修改用户余额,添加余额price值为正，扣除余额price值为负",notes = "返回是否修改成功")
    @ApiImplicitParam(paramType="query",name="price",value="用户余额",required=true)
    public ResponseResult<String> updateBalance(BigDecimal price,HttpServletRequest request){
        int id = GetUserUtil.getUser(request).getId();
        User user = userService.findById(id);
        BigDecimal balance = user.getBalance();
        logger.debug(balance.toString());
        logger.debug("上传数据余额"+price);
        BigDecimal add = balance.add(price);
        if(add.compareTo(BigDecimal.ZERO)==-1){
            return new ResponseResult<>(500,"余额不足",null);
        }
        int i=userService.updateBalance(id,add);
        if (i==1){
            return new ResponseResult<>(200,"修改成功",null);
        }
        return new ResponseResult<>(500,"修改失败",null);

    }

    @PutMapping("/updateuser")
    @ApiOperation(value = "修改账户信息",notes = "返回boolean值，true表示成功，false表示失败")
    public ResponseResult<String> updateUser(@RequestBody User user,HttpServletRequest request){
        logger.debug("修改账户信息");
        boolean updateUser = userService.updateUser(user);
        logger.debug(""+updateUser);
        if(updateUser){
            return new ResponseResult<>(200,"success","修改账户信息成功");
        }{
            return new ResponseResult<>(500,"fail","修改账户信息失败");
        }
    }

    @DeleteMapping ("/delmycoursebyuidcid")
    @ApiOperation(value = "我的课程里面删除我的课程",notes = "返回boolean值，true表示成功，false表示失败")
    @ApiImplicitParam(paramType="query",name="cid",value="课程id",required=true,dataType="Integer")
    public ResponseResult<String> delMyCourseByUidCid(int cid ,HttpServletRequest request){
        User user = GetUserUtil.getUser(request);
        boolean delMyCourseByUidCid = userService.delMyCourseByUidCid(user.getId(), cid);
        if(delMyCourseByUidCid){
            return new ResponseResult<>(200,"success","删除课程成功");
        }{
            return new ResponseResult<>(500,"fail","删除课程失败");
        }
    }


    @DeleteMapping ("/delmycollectionbyuidcid")
    @ApiOperation(value = "我的收藏里面删除我的课程",notes = "返回boolean值，true表示成功，false表示失败")
    @ApiImplicitParam(paramType="query",name="cid",value="课程id",required=true,dataType="Integer")
    public ResponseResult<String> delMyCollectionByUidCid(int cid ,HttpServletRequest request){
        User user = GetUserUtil.getUser(request);
        boolean delMyCollectionByUidCid = userService.delMyCollectionByUidCid(user.getId(), cid);
        if(delMyCollectionByUidCid){
            return new ResponseResult<>(200,"success","删除课程成功");
        }{
            return new ResponseResult<>(500,"fail","删除课程失败");
        }
    }

}
